# -*- coding: utf-8 -*-

import urllib,urllib2,re,xbmcplugin,xbmcgui,os,xbmcaddon,time

##General vars
__plugin__ = "one"
__author__ = "Shmulik"
__hq__ = xbmcaddon.Addon( id=os.path.basename( os.getcwd() ) ).getSetting("hq")


def getMatches(url,pattern,clear=False):
  data = getData(url)
  if (clear):
    data = data.replace("\n","").replace("\t","").replace("\r","")
  matches=re.compile(pattern,re.MULTILINE|re.DOTALL).findall(data)
  return matches

def getData(url):
  print("get:"+url)
  cachePath = xbmc.translatePath( os.path.join( os.getcwd(), 'cache','pages',urllib.quote(url,"") ))
  if (os.path.exists(cachePath) and (time.time()-os.path.getmtime(cachePath))/60/60 <= 1):
    f = open(cachePath, 'r')
    ret = f.read()
    f.close()
    return ret
  data = urllib.urlopen(url).read()
  f = open(cachePath, 'w')
  f.write(data)
  f.close()
  return data
  
def addListItem(isFolder,name,url,mode,infoLabels,iconimage,label_2='',thumb=None,by=""):
  u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&by="+by
  ok=True
  if (thumb==None):
    thumb=iconimage
  liz=xbmcgui.ListItem(name,label_2,iconimage, thumb)
  liz.setInfo( type="Video", infoLabels=infoLabels )
  ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isFolder)
  return ok
  
def addDir(name,url,mode,by,infoLabels,iconimage="DefaultFolder.png"):
   addListItem(True,name,url,mode,infoLabels,iconimage,'',None,by)
   
def addVideo(name,label2,url,mode,infoLabels,thumb="DefaultVideo.png",iconimage="DefaultVideo.png"):
   addListItem(False,name,url,mode,infoLabels,thumb,iconimage)
              
def showCat(id):
  if (int(id) in [41,31,33,52,49,50,20,12,7,43,46,10,9,39,40]):
    u = "http://one.co.il/Cat/Video/First.aspx?ajax=1&c="
  else:
    u = "http://one.co.il/Cat/Video/Reviews.aspx?p=1&t=1&tm=0&r=0&ajax=1&c="
  matches = getMatches(u+str(id),'"Round": (\d+),"Image": "(.*?)",+"Title": "(.*?)","Desc": "(.*?)","League": "(.*?)","Views": "\d+","HQ":"(\w+)","Length":"(.*?)",.*?"ID":(\d+)',True)
  print("founded "+str(len(matches)))
  for round,image,title,desc,league,hq,length,id in matches:
    image = "http://images.one.co.il/images/video/segment165x125/"+image
    addVideo(title.replace('&quot;','"'),desc,id+","+hq,3,{"Duration":length,"Tagline":league + " סיבוב " +round,"Plot":desc},image,image)
    # "סיבוב" stay as UTF need to encode

def showTeam(id):
  u = "http://one.co.il/Cat/Video/Reviews.aspx?p=1&t=1&r=0&ajax=1&tm="
  matches = getMatches(u+str(id),'"Round": (\d+),"Image": "(.*?)","Title": "(.*?)","Desc": "(.*?)","League": "(.*?)","Views": "\d+","HQ":"(\w+)","Length":"(.*?)",.*?"ID":(\d+)',True)
  for round,image,title,desc,league,hq,length,id in matches:
    image = "http://images.one.co.il/images/video/segment165x125/"+image
    addVideo(title.replace('&quot;','"'),desc,id+","+hq,3,{"Duration":length,"Tagline":league + " סיבוב " +round,"Plot":desc},image,image)
    
def getflv(idhq):
  idhq = idhq.split(",")
  hd = -1
  if (idhq[1]=="True" and __hq__=="True"):
    hd = 1
  else:
    hd = 0
  return getMatches("http://svc.one.co.il/Cat/Video/PlaylistFLV.aspx?onetv=1&id="+str(idhq[0])+"&hd="+str(hd),'url="(.*?)"')[1]


    
def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
        return param

def index():
  addDir("קטגוריות","cats",1,"",{"Title":"קטגוריות"})
  addDir("תקצירים לפי קבוצות","teams",1,"",{"Title":"תקצירים לפי קבוצות"})

def listCat():
  cats = getMatches("http://one.co.il/Cat/Video/","<a href='javascript:GoCategory\((\d+)\);'>(.*?)</a>",True)
  for id,title in cats:
      title = title.strip()
      addDir(title,id,2,"cats",{"Title":title})

def listTeams():
  teams = getMatches("http://one.co.il/Cat/Video/Reviews.aspx?tm=0",'<a href="/Cat/Video/Reviews\.aspx\?tm=(\d+)"><img style="border:0;width:46px;height:49px;" src="(.*?)" alt="(.*?)"',True)
  for id,img,title in teams:
      title = title.strip().replace("&quot;",'"')
      addDir(title,id,2,"teams",{"Title":title},img)
  
params=get_params()
url=None
name=None
mode=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass

if mode==None or url==None or len(url)<1:
        index()
elif mode==1:
        if url=="cats":
          listCat()
        else:
          listTeams()
elif mode==2:
        if params["by"]=="cats":
          showCat(url)
        else:
          showTeam(url)
elif mode==3:
        xbmc.Player().play(getflv(url))


xbmcplugin.endOfDirectory(int(sys.argv[1]))

